package com.jiong.gateway.filter;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

@Component
public class JwtGatewayFilter implements GlobalFilter, Ordered {

    // 签名密钥，需要与生成 JWT 的密钥一致
    private static final String TOKEN_SECRET = "jwtSECRET";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, org.springframework.cloud.gateway.filter.GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        // 白名单路径，不需要验证
        String path = request.getURI().getPath();
        if (path.contains("/user/login")) {
            return chain.filter(exchange);
        }

        System.out.println("Token: " + token);

        // 验证 token
        if (token == null || !validateToken(token)) {
            exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // Token 验证成功，继续请求
        return chain.filter(exchange);
    }

    /**
     * 验证 JWT Token
     * @param token JWT token
     * @return 是否有效
     */
    private boolean validateToken(String token) {
        try {
            // 移除 Bearer 前缀
            token = token.replace("Bearer ", "");

            // 使用 HMAC256 加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

            // 验证器
            JWTVerifier verifier = JWT.require(algorithm).build();

            // 解码并验证 Token
            DecodedJWT jwt = verifier.verify(token);

            // 获取 Claims（可以在这里解析用户数据）
            Map<String, Claim> claims = jwt.getClaims();
            String id = claims.get("id").asString();
            System.out.println("Username: " + id);
            return id != null && !id.isEmpty();
        } catch (Exception e) {
            // Token 无效
            return false;
        }
    }

    @Override
    public int getOrder() {
        return -1; // 过滤器优先级
    }
}